﻿#include<iostream>
#include<cmath>
using namespace std;
void doublef(double a,double b,double c){
	double temp,result1,result2;
	temp=b*b-4*a*c;
	if(temp>0.0){
		result1=(-b+sqrt(temp))/(2.0*a);
		result2=(-b-sqrt(temp))/(2.0*a);
		cout<<"方程有两个不同的解:"<<" "<<result1<<'\t'<<result2<<endl;
	}
	else if(temp==0.0){
		result1=(-b+sqrt(temp))/(2.0*a);
		cout<<"方程有两个相同的解:"<<" "<<result1<<endl;
	}
	else{
		cout<<"方程有两个复数解："<<" ";
		cout<<-b/(2.0*a)<<"+j"<<sqrt(-temp)/(2.0*a)<<'\t';
		cout<<-b/(2.0*a)<<"-j"<<sqrt(-temp)/(2.0*a)<<endl;
	}
}
void singlef(double a,double b){
	double result;
	if(a==0.0){
		cout<<"方程无解！"<<endl;
	}
	else{
		result=-b/a;
	}
	cout<<"方程的解是："<<result<<endl;
}
void triblef(double a,double b,double c,double d){
    double A,B,C,delta,Y1,Y2,K,cita,T;
    double x1r,x1i,x2r,x2i,x3r,x3i;
    A=b*b-3.0*a*c;
    B=b*c-9.0*a*d;
    C=c*c-3.0*b*d;
    delta=B*B-4.0*A*C;
    if((A==0.0)&&(B==0.0)){
        x1r=-b/(3.0*a);
        x2r=x1r;x3r=x1r;
        cout<<"方程有三个相同的解："<<" "<<x1r<<'\t'<<x2r<<'\t'<<x3r<<endl;
    }
    else if(delta>0.0){
        Y1=(A*b+3.0*a*(-B+sqrt(B*B-4.0*A*C)))/2.0;
        Y2=(A*b+3.0*a*(-B-sqrt(B*B-4.0*A*C)))/2.0;
        x1r=(-b-3.0*sqrt(Y1)-3.0*sqrt(Y2))/(3.0*a);
        x2r=(-2.0*b+3.0*sqrt(Y1)+3.0*sqrt(Y2))/(6.0*a);
        x2i=(sqrt(3.0)*(3.0*sqrt(Y1)-3.0*sqrt(Y2)))/(6.0*a);
        x3r=x2r;x3i=x2i;
        cout<<"方程有一个实数解："<<" "<<x1r<<endl;
        cout<<"方程有两个复数解："<<" "<<x2r<<"+j"<<x2i<<'\t';
        cout<<x3r<<"-j"<<x3i<<endl;
    }
    else if((delta==0.0)&&(A!=0.0)){
        K=B/A;
        x1r=-b/a+K;
        x2r=-K/2.0;
        x3r=x2r;
        cout<<"方程有三个实数解："<<" "<<x1r<<'\t'<<x2r<<'\t'<<x3r<<endl;
    }
    else if((delta<0.0)&&(A>0.0)){
        T=(2.0*A*b-3.0*a*B)/(2.0*sqrt(A*A*A));
        if((T>=1.0)||(T<=-1.0)){
            cout<<"未定义算法·······"<<endl;
        }
        else{
            cita=acos(T);
            x1r=(-b-2.0*sqrt(A)*cos(cita/3.0))/(3.0*a);
            x2r=(-b+sqrt(A)*cos(cita/3.0)+sqrt(3.0)*sin(cita/3.0))/(3.0*a);
            x3r=(-b+sqrt(A)*cos(cita/3.0)-sqrt(3.0)*sin(cita/3.0))/(3.0*a);
            cout<<"方程有三个实数解："<<" "<<x1r<<'\t'<<x2r<<'\t'<<x3r<<endl;
        }

    }
    else{
        cout<<"未定义算法······"<<endl;
    }
}
int main(){
	int m=1;
	int i=1;
	double a1,b1,a2,b2,c2,a3,b3,c3,d3;
	while((i!=0)&&(m!=0)){
	cout<<"请输入要求解的方程类型，1是一次方程，2是二次方程，3是三次方程，输入0退出程序："<<endl;
	cin>>m;
	if(m==1){
		cout<<"请输入一次方程系数，请从左向右输入："<<endl;
		cin>>a1>>b1;
		singlef(a1,b1);
	}
	else if(m==2){
		cout<<"请输入二次方程系数，请从左向右输入:"<<endl;
		cin>>a2>>b2>>c2;
		doublef(a2,b2,c2);
	}
	else if(m==3){
        cout<<"请输入三次方程系数，请从左向右输入："<<endl;
        cin>>a3>>b3>>c3>>d3;
        triblef(a3,b3,c3,d3);
	}
	else if((m!=1)&&(m!=2)&&(m!=0)&&(m!=3)){
		cout<<"输入错误！"<<endl;
	}
	i++;
	}
	return 0;
}
